import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  FilterOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import {
  ProCard,
  ProForm,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import {
  Avatar,
  Badge,
  Button,
  Card,
  Col,
  Drawer,
  List,
  Modal,
  Popconfirm,
  Progress,
  Row,
  Space,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Tooltip,
  Typography,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";

import React, { useEffect, useState } from "react";

const { Title } = Typography;
const { TabPane } = Tabs;

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
  status: string;
  progress: number;
}

const Page26: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<DataType[]>([]);

  useEffect(() => {
    // 模拟数据加载
    const mockData: DataType[] = [
      {
        key: "1",
        name: "张三",
        age: 32,
        address: "北京市朝阳区",
        tags: ["开发", "前端"],
        status: "active",
        progress: 85,
      },
      {
        key: "2",
        name: "李四",
        age: 28,
        address: "上海市浦东新区",
        tags: ["设计", "UI"],
        status: "inactive",
        progress: 60,
      },
      {
        key: "3",
        name: "王五",
        age: 35,
        address: "广州市天河区",
        tags: ["产品", "管理"],
        status: "active",
        progress: 92,
      },
    ];
    setDataSource(mockData);
  }, []);

  const handleAddClick = () => {
    message.success("点击了新增按钮");
    setModalVisible(true);
  };

  const handleEditClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请先选择要编辑的项目");
      return;
    }
    message.info(`编辑项目: ${selectedRowKeys.join(", ")}`);
    setDrawerVisible(true);
  };

  const handleDeleteClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请先选择要删除的项目");
      return;
    }
    message.success(`删除项目: ${selectedRowKeys.join(", ")}`);
    setSelectedRowKeys([]);
  };

  const handleExportClick = () => {
    message.loading("正在导出数据...", 2).then(() => {
      message.success("数据导出成功！");
    });
  };

  const handleImportClick = () => {
    message.info("点击了导入按钮");
  };

  const handleSearchClick = () => {
    message.info("执行搜索操作");
  };

  const handleFilterClick = () => {
    message.info("打开筛选面板");
  };

  const handleReloadClick = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success("数据刷新完成");
    }, 1000);
  };

  const handleRowClick = (record: DataType) => {
    message.info(`点击了行: ${record.name}`);
  };

  const handleStatusChange = (checked: boolean, record: DataType) => {
    message.success(`${record.name} 状态已${checked ? "启用" : "禁用"}`);
  };

  const handleTagClick = (tag: string) => {
    message.info(`点击了标签: ${tag}`);
  };

  const handleProgressClick = (record: DataType) => {
    message.info(`${record.name} 的进度: ${record.progress}%`);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      render: (text) => (
        <a onClick={() => message.info(`查看 ${text} 详情`)}>{text}</a>
      ),
    },
    {
      title: "年龄",
      dataIndex: "age",
      key: "age",
      sorter: (a, b) => a.age - b.age,
    },
    {
      title: "地址",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "标签",
      key: "tags",
      dataIndex: "tags",
      render: (tags: string[]) => (
        <>
          {tags.map((tag) => (
            <Tag
              key={tag}
              color="blue"
              onClick={() => handleTagClick(tag)}
              style={{ cursor: "pointer" }}
            >
              {tag}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: "状态",
      key: "status",
      dataIndex: "status",
      render: (status: string, record: DataType) => (
        <Switch
          checked={status === "active"}
          onChange={(checked) => handleStatusChange(checked, record)}
        />
      ),
    },
    {
      title: "进度",
      key: "progress",
      dataIndex: "progress",
      render: (progress: number, record: DataType) => (
        <Tooltip title={`点击查看详情`}>
          <div
            onClick={() => handleProgressClick(record)}
            style={{ cursor: "pointer" }}
          >
            <Progress percent={progress} size="small" />
          </div>
        </Tooltip>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => message.info(`编辑 ${record.name}`)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除吗？"
            onConfirm={() => message.success(`删除 ${record.name}`)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}>页面 26 - 复杂数据管理</Title>

      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={1128}
              prefix={<Badge count={1128} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={856}
              valueStyle={{ color: "#3f8600" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日新增"
              value={23}
              valueStyle={{ color: "#cf1322" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="完成率" value={93.2} suffix="%" precision={1} />
          </Card>
        </Col>
      </Row>

      <ProCard>
        <Tabs defaultActiveKey="1">
          <TabPane tab="数据列表" key="1">
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddClick}
              >
                新增
              </Button>
              <Button icon={<EditOutlined />} onClick={handleEditClick}>
                编辑
              </Button>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleDeleteClick}
              >
                删除
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExportClick}>
                导出
              </Button>
              <Button icon={<UploadOutlined />} onClick={handleImportClick}>
                导入
              </Button>
              <Button icon={<SearchOutlined />} onClick={handleSearchClick}>
                搜索
              </Button>
              <Button icon={<FilterOutlined />} onClick={handleFilterClick}>
                筛选
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReloadClick}>
                刷新
              </Button>
            </Space>

            <Table
              columns={columns}
              dataSource={dataSource}
              loading={loading}
              rowSelection={{
                selectedRowKeys,
                onChange: setSelectedRowKeys,
              }}
              onRow={(record) => ({
                onClick: () => handleRowClick(record),
              })}
              pagination={{
                total: dataSource.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              }}
            />
          </TabPane>

          <TabPane tab="表单操作" key="2">
            <ProForm
              onFinish={async (values) => {
                message.success("表单提交成功！");
                console.log(values);
              }}
              submitter={{
                searchConfig: {
                  submitText: "提交",
                  resetText: "重置",
                },
              }}
            >
              <ProFormText
                name="name"
                label="姓名"
                placeholder="请输入姓名"
                rules={[{ required: true, message: "请输入姓名" }]}
              />
              <ProFormSelect
                name="type"
                label="类型"
                options={[
                  { label: "类型A", value: "a" },
                  { label: "类型B", value: "b" },
                  { label: "类型C", value: "c" },
                ]}
                placeholder="请选择类型"
                rules={[{ required: true, message: "请选择类型" }]}
              />
            </ProForm>
          </TabPane>

          <TabPane tab="详细信息" key="3">
            <List
              itemLayout="horizontal"
              dataSource={dataSource}
              renderItem={(item) => (
                <List.Item
                  actions={[
                    <Button
                      key="edit"
                      type="link"
                      onClick={() => message.info(`编辑 ${item.name}`)}
                    >
                      编辑
                    </Button>,
                    <Button
                      key="delete"
                      type="link"
                      danger
                      onClick={() => message.info(`删除 ${item.name}`)}
                    >
                      删除
                    </Button>,
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar>{item.name.charAt(0)}</Avatar>}
                    title={
                      <a onClick={() => message.info(`查看 ${item.name} 详情`)}>
                        {item.name}
                      </a>
                    }
                    description={`${item.age}岁 | ${item.address}`}
                  />
                  <div>
                    <Progress percent={item.progress} size="small" />
                    <div style={{ marginTop: 8 }}>
                      {item.tags.map((tag) => (
                        <Tag
                          key={tag}
                          color="blue"
                          onClick={() => handleTagClick(tag)}
                        >
                          {tag}
                        </Tag>
                      ))}
                    </div>
                  </div>
                </List.Item>
              )}
            />
          </TabPane>
        </Tabs>
      </ProCard>

      <Modal
        title="新增项目"
        open={modalVisible}
        onOk={() => {
          message.success("新增成功！");
          setModalVisible(false);
        }}
        onCancel={() => setModalVisible(false)}
      >
        <p>这里是新增项目的表单内容</p>
      </Modal>

      <Drawer
        title="编辑项目"
        placement="right"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        width={400}
      >
        <p>这里是编辑项目的表单内容</p>
      </Drawer>
    </div>
  );
};

export default Page26;
